//
//  LoginViewController.m
//  CS Inventory Manager
//
//  Created by Billy Zoellers on 4/7/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"

@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize inUsername,inPassword,theUsername,thePassword;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.navigationItem.rightBarButtonItem setEnabled:NO];
    
    // get paths from root direcory
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    // get documents path
    NSString *documentsPath = [paths objectAtIndex:0];
    // get the path to our Data/plist file
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"UserInfo.plist"];
	
    // check to see if Data.plist exists in documents
    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
    {
        // if not in documents, get property list from main bundle
		NSError *error;
		NSString *OSplistPath = [[NSBundle mainBundle] pathForResource:@"UserInfo" ofType:@"plist"];
		[[NSFileManager defaultManager] copyItemAtPath:OSplistPath toPath:plistPath error:&error];
		NSLog(@"creating from bundle");
    }
	
    // read property list into memory as an NSData object
    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
	NSLog(@"reading from plist at %@", plistPath);
    NSString *errorDesc = nil;
    NSPropertyListFormat format;
    // convert static property liost into dictionary object
    NSDictionary *plistAccess = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
    if (!plistAccess)
    {
        NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
    }
    
	// Go ahead and pull name from plist
	if ([plistAccess objectForKey:@"username"]) {
		
		theUsername = [[NSString alloc] initWithString:[plistAccess objectForKey:@"username"]];
        thePassword = [[NSString alloc] initWithString:[plistAccess objectForKey:@"password"]];
		
	}


    // enable the button if the info is already filled in
    if (theUsername.length && thePassword.length) {
        [self.navigationItem.rightBarButtonItem setEnabled:YES];
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)loginButton:(id)sender {
    [inPassword resignFirstResponder];
    
    // check the web auth
    // generate the URL and use %20 encoding
    NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/login.php?secret=pass&u=%@&p=%@",inUsername.text, inPassword.text];
    NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"The url is: >>>>>%@<<<<<", final);
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
    
    // make web request and catch error
    NSError * e;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
    
    // log the value returned from the web server
    NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"return from web: %@", value);
    
    // get authentication response from web
    int webResponse = [[[value componentsSeparatedByString:@"*"] objectAtIndex:1] integerValue];
    
    if (webResponse) {
        NSLog(@"Login allowed");
        
        // store important data in AppDelegate
        int profId = [[[value componentsSeparatedByString:@"*"] objectAtIndex:3] integerValue];
        NSLog(@"Professor ID: %i",profId);
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDelegate setLoggedInProfessorId:profId];
        [appDelegate setLoggedInProfessorEmail:inUsername.text];
        
        // Store back into plist
        // write to plist
        NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
        // get documents path
        NSString *documentsPath = [paths objectAtIndex:0];
        // get the path to our Data/plist file
        NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"UserInfo.plist"];
        NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:inUsername.text,inPassword.text,nil] forKeys:[NSArray arrayWithObjects:@"username",@"password",nil]];
        
        NSString *error = nil;
        // create NSData from dictionary
        NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
        
        // check is plistData exists
        if(plistData)
        {
            NSLog(@"writing to %@", plistPath);
            // write plistData to our Data.plist file
            [plistData writeToFile:plistPath atomically:YES];
        }
        
        
        [self performSegueWithIdentifier:@"LateItems" sender:nil];
        // [self dismissViewControllerAnimated:YES completion:nil];
        
    } else {
        NSLog(@"Login not allowed");
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Login invalid." message:@"The username or password you have enterned is not recognized. Please try again." delegate:self cancelButtonTitle:@"Dismiss"  otherButtonTitles:nil, nil];
        [alert show];
        alert = nil;
        
    }
    
    
    
}

#pragma mark - Text Field Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    
    if (theTextField == inUsername) {
        [inPassword becomeFirstResponder];
    } else if (theTextField == inPassword) {
        [inPassword resignFirstResponder];
        // done button also hits login button
        [self loginButton:nil];
    }
    
    return YES;
}

    
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField == inPassword) {
        [self.navigationItem.rightBarButtonItem setEnabled:YES];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"loginCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    cell.detailTextLabel.text = @"";
    
    // make a text field
    UITextField *inputTextField = [[UITextField alloc] initWithFrame:CGRectMake(85, 10, 395, 30)];
    inputTextField.adjustsFontSizeToFitWidth = YES;
    inputTextField.textColor = [UIColor blackColor];
    inputTextField.backgroundColor = [UIColor clearColor];
    inputTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    inputTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    inputTextField.tag = 0;
    inputTextField.clearButtonMode = UITextFieldViewModeNever;
    [inputTextField setEnabled: YES];
    inputTextField.delegate = self;
    
    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = @"Email";
            inputTextField.text = theUsername;
            inputTextField.returnKeyType = UIReturnKeyNext;
            self.inUsername = inputTextField;
            [cell.contentView addSubview:inputTextField];
            inputTextField = nil;
            
            break;
        case 1:
            cell.textLabel.text = @"Password";
            inputTextField.text = thePassword;
            inputTextField.returnKeyType = UIReturnKeyDone;
            inputTextField.secureTextEntry = YES; // password
            self.inPassword = inputTextField;
            [cell.contentView addSubview:inputTextField];
            inputTextField = nil;
            
            break;
    }

    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

@end
